#include <stdio.h>
#include <libavformat/avformat.h>
#include <libavcodec/codec.h>
#include <unistd.h>
#include <libswscale/swscale.h>



AVFormatContext * myavformat=NULL;
AVCodec *myavcode = NULL;
AVPacket *mypkt=NULL;
AVFrame *myavframe = NULL;
AVFrame *myavframeout = NULL;
struct SwsContext *mysws=NULL;

uint8_t argb_buf[800*480*4]= {0};
void rgb_to_argb(uint8_t *rgbdata,uint8_t *argbdata,int w,int h)
{
	int i = 0,j = 0;
	for(i=0;i<h;i++)
	{
		for(j=0;j<w;j++)
		{
			argbdata[j*4+i*w*4+3] = 0xFF;//透明度
			argbdata[j*4+i*w*4+0]=rgbdata[j*3+j*w*3+2];
			argbdata[j*4+i*w*4+1]=rgbdata[j*3+j*w*3+1];
			argbdata[j*4+i*w*4+2]=rgbdata[j*3+j*w*3+0];
			
		}
	}
}

int main()
{
	//1.初始化ffmpeg所支持的所有协议
	void av_register_all();
	//2.申请音视频上下文结构体
	myavformat = avformat_alloc_context();
	//3.打开文件
	avformat_open_input(&myavformat,"/home/lx/tools/1.mp4",NULL,NULL);
	//4.查看文件流媒体信息
	avformat_find_stream_info(myavformat, NULL);
	//5.查找解码器
	myavcode = avcodec_find_decoder(myavformat->streams[0]->codecpar->codec_id);
	//6.初始化解码器
	avcodec_open2(myavformat->streams[0]->codec , myavcode, NULL);

	mypkt = av_packet_alloc();
	myavframe = av_frame_alloc(); 
	myavframeout =av_frame_alloc();

	mysws = sws_getContext(myavformat->streams[0]->codecpar->width, myavformat->streams[0]->codecpar->height, myavformat->streams[0]->codec->pix_fmt, 800, 480, AV_PIX_FMT_RGB24, SWS_GAUSS, NULL, NULL, NULL);

	uint8_t *out = av_malloc(av_image_get_buffer_size( AV_PIX_FMT_RGB24, 800, 480, 1));
	av_image_fill_arrays(myavframeout->data, myavframeout->linesize, out, AV_PIX_FMT_RGB24, 800, 480, 1);
	//从上下文结构体读取一帧的数据
	while(av_read_frame(myavformat, mypkt)==0)
	{
		if(mypkt->stream_index == 0)
		{
		     //将视频数据发送给解码器
			avcodec_send_packet(myavformat->streams[0]->codec,mypkt);
			//从解码器获取一帧解码后的视频数据
			avcodec_receive_frame(myavformat->streams[0]->codec, myavframe);
			printf("一帧数据解码成功\n");
			sws_scale(mysws, myavframe->data, myavframe->linesize, 0, myavframe->height, myavframeout->data, myavframeout->linesize);

			rgb_to_argb(out,argb_buf, 800, 480);

			usleep(33333);
		}	
	}
	return 0;
	
}